package bkone;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/user_login")
public class user_login_servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public static List<Map<String, String>> remoteUserInfos = new ArrayList<>();
	private static final String JDBC_URL = "jdbc:mysql://localhost:3309/blog?useUnicode=true&characterEncoding=utf8";
	private static final String DB_USER = "root";
	private static final String DB_PWD = "ZLWL";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public user_login_servlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String webResult = "";
		request.setAttribute("name", "value");

		// 1.加载注册驱动
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		}

		// 2.建立数据连接
		Connection conn;
		try {
			conn = DriverManager.getConnection(JDBC_URL, DB_USER, DB_PWD);

			// 3.执行SQL语句
			// 建立Statement对象
			Statement stmt = conn.createStatement();

			// 做好准备工作之后就可以执行sql语句了
			String sqla = "select * from user_zc where name = '" + name + "'";

			// 执行sql语句
			ResultSet rs = stmt.executeQuery(sqla);

			// 4.处理数据
			boolean exists = false;
			boolean existss = false;
			while (rs.next()) {
				exists = true;
				System.out.println("的确有" + rs.getString("name") + "用户");
			}

			response.setCharacterEncoding("utf-8");
			if (exists) {
				String sqlpw  = "select * from user_zc where name = '" + name + "'";
				System.out.println("1");
				ResultSet rspw = stmt.executeQuery(sqlpw);
				System.out.println("2");
				System.out.println(rspw);
				while (rspw.next()) {
					String getpw = rspw.getString("password");
					System.out.println(getpw);
					if (getpw.equals(password)) {
						existss = true;
					}
				}
			} else {
				response.getWriter().write("登录失败，不存在该用户");
			}

			if (existss) {
				webResult = "登录成功！";
				System.out.println("登录成功！");
				response.getWriter().write("登录成功");
				
				SimpleDateFormat sdfFull1 = new SimpleDateFormat("yyyy-MM-dd ");
				SimpleDateFormat sdfFull2 = new SimpleDateFormat(":mm:ss");
				Calendar cld = Calendar.getInstance();
				Date currentDate = new Date();
				System.out.println("完整的(前)：" + sdfFull1.format(currentDate));
				System.out.println("完整的(后)：" + sdfFull2.format(currentDate));
				System.out.println("当前天,时间：" + cld.get(Calendar.HOUR_OF_DAY));
				String login_time = sdfFull1.format(currentDate) + cld.get(Calendar.HOUR_OF_DAY) + sdfFull2.format(currentDate);
				

				//登陆信息录入数据库
				String sqlluru = "insert into user (account,password,name,avt,login_time) values(?,?,?,?,?)";
				PreparedStatement pstmt = conn.prepareStatement(sqlluru);
				pstmt.setString(1, null);
				pstmt.setString(2, password);
				pstmt.setString(3, name);
				pstmt.setString(4, null);
				pstmt.setString(5, login_time);
				int insertResult = pstmt.executeUpdate();
				
				if (insertResult > 0) {
					response.getWriter().write("{'ok':true}");
				} else {
					response.getWriter().write("{'ok':false}");
				}
				
				pstmt.close();

				HttpSession session = request.getSession();
		        session.setAttribute("passwordt", password);  
		        session.setAttribute("namet", name); 
		        System.out.println(password);
		        System.out.println(name);
				response.sendRedirect("/jump_success.html");
			} else {
				webResult = "登录失败！用户名或密码错误！";
				System.out.println("登录失败！用户名或密码错误！");
				response.getWriter().write("登录失败！用户名或密码错误");
				response.sendRedirect("/jump_failure.html");
			}
			// 5.关闭连接
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		response.setCharacterEncoding("utf-8");
		response.addCookie(new Cookie("userid", "test"));

		response.getWriter().append("登录结果: " + webResult);

	}

}